<template>
  <div class="equipment-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">设备档案</h2>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 操作栏 -->
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
            新增设备
          </el-button>
          <el-button type="success" @click="handleMaintenance" icon="el-icon-s-tools">
            设备维修
          </el-button>
        </div>
        <div class="action-right">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入小区/设备名称/设备编码"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-button 
                type="primary" 
                icon="el-icon-search" 
                @click="handleSearch"
                class="search-btn"
              />
            </template>
          </el-input>
          <el-button 
            type="default" 
            icon="el-icon-s-operation" 
            @click="showFilterDialog = true"
            class="filter-btn"
          >
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="communityName" label="小区" width="100" align="center" />
          <el-table-column prop="equipmentName" label="设备名称" width="80" align="center" />
          <el-table-column prop="equipmentCode" label="设备编码" width="100" align="center" />
          <el-table-column prop="equipmentCategoryName" label="设备类别" width="80" align="center" />
          <el-table-column prop="maintenanceUnit" label="单位" width="60" align="center" />
          <el-table-column prop="equipmentStatusName" label="设备状态" width="80" align="center">
            <template #default="scope">
              <el-tag 
                :type="getStatusTagType(scope.row.equipmentStatus)"
                size="small"
              >
                {{ scope.row.equipmentStatusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="manufacturer" label="生产厂家" width="80" align="center" />
          <el-table-column prop="equipmentMaintainer" label="责任人" width="60" align="center" />
          <el-table-column prop="installationDate" label="安装日期" width="100" align="center" />
          <el-table-column prop="maintenanceNum" label="保养次数" width="50" align="center" />
          <el-table-column prop="repairNum" label="维修次数" width="50" align="center" />
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="handleDetail(scope.row)"
                class="action-link"
              >
                详情
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="handleDelete(scope.row)"
                class="action-link delete-link"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, jumper, sizes, total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 筛选对话框 -->
    <el-dialog
      v-model="showFilterDialog"
      title="筛选条件"
      width="500px"
      :before-close="handleFilterClose"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="设备状态">
          <el-select v-model="filterForm.equipmentStatus" placeholder="请选择设备状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="故障" :value="2" />
            <el-option label="维修中" :value="3" />
            <el-option label="停用" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类别">
          <el-select v-model="filterForm.equipmentCategory" placeholder="请选择设备类别" clearable>
            <el-option label="电梯" :value="1" />
            <el-option label="空调" :value="2" />
            <el-option label="消防设备" :value="3" />
            <el-option label="照明设备" :value="4" />
            <el-option label="给排水设备" :value="5" />
            <el-option label="安防设备" :value="6" />
            <el-option label="广告设备" :value="7" />
            <el-option label="其他设备" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装日期">
          <el-date-picker
            v-model="filterForm.installationDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleFilterClose">取消</el-button>
          <el-button type="primary" @click="handleFilterConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑设备弹框 -->
    <EditEquipmentDialog
      v-model="showEditDialog"
      :equipment-data="currentEquipment"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { equipmentApi } from '@/api/equipment'
import EditEquipmentDialog from '@/components/EditEquipmentDialog.vue'
import request, { communityRequest } from '@/utils/request'

export default {
  name: 'EquipmentManagement',
  components: {
    EditEquipmentDialog
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 搜索参数
      searchKeyword: '',
      
      // 筛选参数
      showFilterDialog: false,
      filterForm: {
        equipmentStatus: null,
        equipmentCategory: null,
        installationDateRange: null
      },
      
      // 编辑弹框参数
      showEditDialog: false,
      currentEquipment: {},
      
      // 设备状态映射
      statusMap: {
        1: '正常',
        2: '故障', 
        3: '维修中',
        4: '停用'
      },
      
      // 设备类别映射
      categoryMap: {
        1: '电梯',
        2: '空调',
        3: '消防设备',
        4: '照明设备',
        5: '给排水设备',
        6: '安防设备',
        7: '广告设备',
        8: '其他设备'
      }
    }
  },
  
  mounted() {
    this.loadData()
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          title: this.searchKeyword || null,
          ...this.getFilterParams()
        }
        
        console.log('请求参数:', params)
        const response = await equipmentApi.getEquipmentPage(params)
        console.log('API响应:', response)
        
        if (response.code === 200) {
          this.tableData = this.formatTableData(response.data.records || [])
          this.total = response.data.total || 0
          console.log('表格数据:', this.tableData)
        } else {
          this.$message.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败: ' + (error.message || '网络错误'))
      } finally {
        this.loading = false
      }
    },
    
    // 格式化表格数据
    formatTableData(data) {
      return data.map(item => ({
        ...item,
        equipmentStatusName: this.statusMap[item.equipmentStatus] || '未知',
        equipmentCategoryName: this.categoryMap[item.equipmentCategory] || '未知',
        communityName: item.communityName || '未分配小区',
        maintenanceUnit: '个', // 默认单位
        installationDate: item.installationDate ? this.formatDate(item.installationDate) : '-',
        maintenanceNum: item.maintenanceNum || 0,
        repairNum: item.repairNum || 0
      }))
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      const d = new Date(date)
      return d.getFullYear() + '-' + 
             String(d.getMonth() + 1).padStart(2, '0') + '-' + 
             String(d.getDate()).padStart(2, '0')
    },
    
    // 获取筛选参数
    getFilterParams() {
      const params = {}
      if (this.filterForm.equipmentStatus) {
        params.equipmentStatus = this.filterForm.equipmentStatus
      }
      if (this.filterForm.equipmentCategory) {
        params.equipmentCategory = this.filterForm.equipmentCategory
      }
      if (this.filterForm.installationDateRange && this.filterForm.installationDateRange.length === 2) {
        params.startDate = this.filterForm.installationDateRange[0]
        params.endDate = this.filterForm.installationDateRange[1]
      }
      return params
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        1: 'success',  // 正常
        2: 'danger',   // 故障
        3: 'warning',  // 维修中
        4: 'info'      // 停用
      }
      return typeMap[status] || 'info'
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    
    // 筛选确认
    handleFilterConfirm() {
      this.currentPage = 1
      this.loadData()
      this.showFilterDialog = false
    },
    
    // 筛选关闭
    handleFilterClose() {
      this.showFilterDialog = false
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadData()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    
    // 新增设备
    handleAdd() {
      this.$router.push('/equipment-management/add-equipment')
    },
    
    // 跳转到设备维修管理
    handleMaintenance() {
      this.$router.push('/equipment-management/equipment-maintenance')
    },
    
    // 查看详情
    handleDetail(row) {
      this.$router.push(`/equipment-management/equipment-detail/${row.equipmentId}`)
    },
    
    // 编辑设备
    handleEdit(row) {
      this.currentEquipment = { ...row }
      this.showEditDialog = true
    },
    
    // 编辑成功回调
    handleEditSuccess() {
      this.loadData() // 重新加载数据
    },
    
    // 删除设备
    handleDelete(row) {
      this.$confirm(`确定要删除设备 "${row.equipmentName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await equipmentApi.deleteEquipment(row.equipmentId)
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 初始化测试数据
    async handleInitTestData() {
      this.$confirm('确定要初始化设备测试数据吗？这将创建一些示例设备数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await equipmentApi.initTestData()
          if (response.code === 200) {
            this.$message.success(response.message || '初始化成功')
            this.loadData() // 重新加载数据
          } else {
            this.$message.error(response.message || '初始化失败')
          }
        } catch (error) {
          console.error('初始化失败:', error)
          this.$message.error('初始化失败: ' + (error.message || '网络错误'))
        }
      }).catch(() => {
        this.$message.info('已取消初始化')
      })
    },

    // 初始化所有测试数据
    async handleInitAllTestData() {
      this.$confirm('确定要初始化所有测试数据吗？这将创建社区、设备等示例数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 先初始化社区数据
          const communityResponse = await communityRequest({
            url: '/community/initTestData',
            method: 'post'
          })
          console.log('社区数据初始化结果:', communityResponse)
          
          // 再初始化设备数据
          const equipmentResponse = await equipmentApi.initTestData()
          console.log('设备数据初始化结果:', equipmentResponse)
          
          if (equipmentResponse.code === 200) {
            this.$message.success('所有测试数据初始化成功')
            this.loadData() // 重新加载数据
          } else {
            this.$message.error('设备数据初始化失败: ' + (equipmentResponse.message || '未知错误'))
          }
        } catch (error) {
          console.error('初始化失败:', error)
          this.$message.error('初始化失败: ' + (error.message || '网络错误'))
        }
      }).catch(() => {
        this.$message.info('已取消初始化')
      })
    }
  }
}
</script>

<style scoped>
.equipment-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #ebeef5;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.search-btn {
  margin-left: 5px;
}

.filter-btn {
  margin-left: 5px;
}

.table-container {
  padding: 0 30px;
}

.action-link {
  color: #409EFF;
  text-decoration: none;
  margin: 0 5px;
}

.action-link:hover {
  color: #66b1ff;
}

.delete-link {
  color: #F56C6C;
}

.delete-link:hover {
  color: #f78989;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .equipment-management {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .action-right {
    justify-content: space-between;
  }
  
  .search-input {
    width: 200px;
  }
  
  .table-container {
    padding: 0 15px;
    overflow-x: auto;
  }
  
  .pagination-container {
    padding: 15px;
  }
}
</style>